<template>
  <view class="knowledge-test">
    <!-- <view class="header">
      <text>健康常识小测验</text>
    </view> -->
    <view class="question">
      <text class="title">{{ currentTest.title }}</text>
      <text class="content">
        {{ currentTest.description }}
      </text>
      <view class="options">
        <view
          class="question-item"
          v-for="option in currentTest.options"
          :key="option.id"
          :class="{ active: chooseOptionId == option.id }"
          @tap="makeChoice(option)"
        >
          {{ option.content }}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import Taro from "@tarojs/taro";
import "./index.less";
import {
  getTodayTests,
  submitTest
} from "../../../services/healthy-test-service";
export default {
  data() {
    return {
      testSeq: 0,
      todayTests: [],
      chooseOptionId: null
    };
  },
  methods: {
    async makeChoice(option) {
      const { healthTestId, id } = option;
      this.chooseOptionId = id;
      const res = await submitTest({
        healthTestId,
        optionId: id
      });
      if (res.data.code === "success") {
        // TODO: 确认后端返回的healthTestId是否代表当前正确的答案
        const correctContent = this.currentTest.options.find(
          option => option.healthTestId === res.data.data.healthTestId
        );
        const { score, correct, description } = res.data.data;
        const testDetail = {
          title: this.currentTest.title,
          score,
          correct,
          correctContent: correctContent.content,
          description
        };
        this.$store.commit("setTestDetail", testDetail);

        Taro.navigateTo({
          url: "/pages/health-questionnaire/knowledge-test/answer-detail/index"
        });
      }
    },
    async getTodayTests() {
      this.todayTests = await getTodayTests();
      this.$store.commit("setTodayTests", this.todayTests);
    }
  },
  computed: {
    currentTest() {
      return this.todayTests.length > 0
        ? this.todayTests[this.testSeq]
        : { title: "", description: "", options: [] };
    }
  },
  async created() {
    this.testSeq = this.$store.state.healthyTest.testSeq;

    this.todayTests = this.$store.state.healthyTest.todayTests;
    if (this.todayTests.length <= 0) {
      this.getTodayTests();
    }
  }
};
</script>
